<template>
  <div>
    <el-dialog
      v-model="open"
      title="课题申请"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
      :modal="true"
      class="dialog-centered"
      :draggable="false"
      :custom-class="'dialog-custom'"
    >
      <!-- 添加 el-form 包裹 -->
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 课题名称 -->
        <el-form-item label="课题名称" prop="topicName" required>
          <el-input v-model="form.topicName" placeholder="请输入课题名称（必填）" />
        </el-form-item>

        <!-- 选择流程 -->
        <el-form-item label="选择流程" prop="definitionId" required class="disabled-color">
          <el-input
            v-model="form.definitionName"
            placeholder="请根据下列表格进行流程选择（必填）"
            readonly="readonly"
          />
        </el-form-item>
      </el-form>

      <!-- 流程选择部分（添加滚动条样式） -->
      <div style="max-height: 300px; overflow-y: auto;">
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="queryForm" class="demo-form-inline">
          <el-form-item label="流程名称">
            <el-input v-model="queryForm.definitionName" placeholder="请输入流程名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格显示流程列表 -->
        <el-table v-loading="loading" :data="filteredList">
          <el-table-column label="流程名称" align="center" prop="name" />
          <el-table-column>
            <template #default="scope">
              <el-button link type="primary" @click="handleSelect(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          layout="prev, pager, next"
          v-model:page-size="queryForm.pageSize"
          v-model:current-page="queryForm.pageNo"
          :total="total"
          @current-change="getList"
        />
      </div>

      <!-- 主表单 -->
      <el-card class="box-card" v-if="Object.keys(form.formJson).length!== 0">
        <template #header>
          <div class="card-header">
            <span>主表单</span>
          </div>
        </template>
        <VFormRender ref="preForm" />
      </el-card>

      <!-- 按钮 -->
      <template #footer>
        <div style="display: flex; justify-content: center;">
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRef, nextTick, computed } from "vue";
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
import VFormRender from "@/components/FormDesigner/form-render/index.vue";

// 表单可编辑状态
const isEditable = ref(false);
// 动态表单实例
const preForm = ref();
// 表单实例
const formRef = ref();
// 提交表单数据
let form = toRef(
  reactive({
    businessKey: "",
    formId: "",
    formName: "",
    formJson: {},
    definitionId: "",
    definitionName: "",
    topicName: ""
  })
);

// 表单验证规则
const rules = ref({
  topicName: [{ required: true, message: "请输入课题名称", trigger: "blur" }],
  definitionId: [{ required: true, message: "请选择流程", trigger: "blur" }]
});

// 初始化
const init = () => {
  open.value = true;
  const generatedKey = generateKey(10);
  form.value.businessKey = generatedKey;
  isEditable.value = true;
  form.value = {
 ...form.value,
    formId: "",
    formName: "",
    formJson: {},
    definitionId: "",
    definitionName: "",
    topicName: ""
  };
  nextTick(() => {
    preForm.value?.setFormJson({});
    formRef.value?.resetFields();
    getList(); // 在初始化时获取流程列表数据
  });
};

// 选择流程返回数据
const selectProcessOk = (data: any) => {
  form.value.definitionId = data.id;
  form.value.definitionName = data.name;
  form.value.formJson = data.formJson || {};
  nextTick(() => {
    preForm.value?.setFormJson(form.value.formJson);
  });
};

// 提交按钮
function submitForm() {
  formRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      // 表单验证失败时提示错误信息
      ElMessage.error("请填写必填项");
      return;
    }

    const formData = (await preForm.value?.getFormData()) || {};

    const subForm = {
      businessKey: form.value.businessKey,
      definitionId: form.value.definitionId,
      topicName: form.value.topicName,
      variables: {
     ...JSON.parse(JSON.stringify(formData)),
        [`${form.value.businessKey}_formData`]: formData,
        [`${form.value.businessKey}_formJson`]: form.value.formJson,
      },
    };

    // 提交表单数据
    baseService.post(`/processStart/start`, subForm).then((res) => {
      if (res.code === 200) {
        ElMessage.success(res.msg);
        open.value = false;
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
}

// 生成业务key
function generateKey(length: number) {
  const prefix = "ServiceKey_";
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let randomPart = '';

  for (let i = 0; i < length; i++) {
    randomPart += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return prefix + randomPart;
}

// 查询参数
const queryForm = reactive({
  definitionName: "",
  definitionKey: "",
  active: true,
  pageNo: 1,
  pageSize: 10
});

// 列表相关数据
const total = ref(0);
const loading = ref(true);
const list = ref<any[]>([]);

// 控制弹出框的显示和隐藏
const open = ref(false);

// 获取流程定义列表
const getList = () => {
  loading.value = true;
  baseService
 .get("/processDefinition/list", queryForm)
 .then((res) => {
      loading.value = false;
      if (res.code === 200) {
        list.value = res.rows;
        total.value = res.total;
      } else {
        list.value = [];
      }
    })
 .catch(() => {
      loading.value = false;
    });
};

// 重置搜索条件
function handleReset() {
  queryForm.definitionName = "";
  queryForm.pageNo = 1;
  getList();
}

// 选择流程行后触发
function handleSelect(row: any) {
  form.value.definitionId = row.id;
  form.value.definitionName = row.name;
  form.value.formJson = row.formJson || {};
  nextTick(() => {
    preForm.value?.setFormJson(form.value.formJson);
  });
}

// 使用 computed 属性进行筛选
const filteredList = computed(() => {
  return list.value.filter((item) => item.name.includes(queryForm.definitionName));
});

// 对外暴露的方法
defineExpose({
  init
});
</script>

<style scoped>
.dialog-centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.dialog-custom {
  top: 50%!important;
  transform: translateY(-50%)!important;
}
.el-dialog__header {
  cursor: default!important;
}
</style>